package com.weilive.pay.gate;

import java.net.URLDecoder;
import java.util.Map;

import org.jboss.netty.handler.codec.http.HttpRequest;
import org.jboss.netty.handler.codec.http.HttpResponse;
import org.jboss.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.weilive.core.netty.http.HttpServlet;
import com.weilive.core.utils.HttpUtils;
import com.weilive.pay.msg.ToPayMsg;
import com.weilive.pay.service.apple.ApplePayService;

/**
 * apple支付
 * 
 * @author
 *
 */
@Service
public class ApplePayServlet extends HttpServlet {
	private static final Logger logger = LoggerFactory.getLogger(ApplePayServlet.class);
	@Autowired
	private ApplePayService applePayService;

	@Override
	public String getServletPath() {
		return "/pay/applepay";
	}

	@Override
	public HttpResponse processRequest(HttpRequest request) throws Exception {
		// post
		String temStr = URLDecoder.decode(request.getContent().toString(CharsetUtil.UTF_8), "UTF-8");
		// 处理支付结果
		// 获取支付宝POST过来反馈信息
		Map<String, String> params = HttpUtils.getParamsMap(temStr);

		if (params.isEmpty()) {
			String toMsg = new ToPayMsg("0", "参数错误", null, null).toString();
			return createJsonResponse(toMsg);
		}
		try {
			long userId = Long.parseLong(params.get("userId"));
			String recipe = params.get("recipe");

			// 去掉空格
			recipe = recipe != null ? recipe.trim() : "";

			String check = applePayService.checkAndSaveLog(userId, recipe);

			if (!check.equals("ok")) {
				String toMsg = new ToPayMsg("0", check, null, null).toString();
				logger.info("收到苹果支付通知, params=" + params.toString() + ",返回结果=" + toMsg);
				return createJsonResponse(toMsg);
			}

			String toMsg = applePayService.applePay(userId, recipe);

			logger.info("收到苹果支付通知, params=" + params.toString() + ",返回结果=" + toMsg);
			return createJsonResponse(toMsg);

		} catch (Exception e) {
			e.printStackTrace();
			String toMsg = new ToPayMsg("0", "内部错误", null, null).toString();
			logger.info("收到苹果支付通知, params=" + params.toString() + ",返回结果=" + toMsg);
			return createJsonResponse(toMsg);
		}

	}
}